package com.fxw.config;

import com.fxw.em.DatabaseType;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName DBContextHolder
 * @Deacription TODO
 * @Author hqq
 * @Date 2021/10/25 21:58
 * @Version 1.0
 **/
public class DBContextHolder {

    /**
     * 创建线程安全的类，作为databaseType容器，放master,slave
     */
    private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();

    private static final AtomicInteger counter = new AtomicInteger(-1);

    public static void set(DatabaseType databaseType) {
        contextHolder.set(databaseType);
    }

    public static DatabaseType get() {

        return contextHolder.get();
    }

    public static void setDataBaseMaster() {
        set(DatabaseType.MASTER);
        System.out.println("切换到master");
    }

    public static void setDataBaseSlave() {
        //  轮询
        // int index = counter.getAndIncrement() % 2;
        // if (counter.get() > 9999) {
        //    counter.set(-1);
        //  }
        //if (index == 0) {
        set(DatabaseType.SLAVE);
        System.out.println("切换到slave");
        // }
    }
}
